""" Clock generators used in testing """

from myhdl import always, Signal, Simulation, instance, instances, delay, now, traceSignals

def clk_driver(Clk, highTime=1, lowTime=1):
    """ Very simple clock driver

    Clk -- the signal that is to be driven
    highTime -- the Clk will be high for delay highTime
    lowTime -- the Clk will be low for delay lowTime

    """

    @instance
    def drive_clk():
        if 1 == Clk.val:
            delay_1 = highTime
            delay_2 = lowTime
        else:
            delay_1 = lowTime
            delay_2 = highTime

        while True:
            yield delay(delay_1)
            Clk.next = not Clk
            yield delay(delay_2)
            Clk.next = not Clk

    return drive_clk

###################################################################################################
# Tests
###################################################################################################

def even_duty_cycle():
    Clk = Signal(bool(0))
    timeStepClk = Signal(bool(0))
    mut = clk_driver(Clk, highTime=2, lowTime=2)
    oldClk = Signal(bool(1))

    @always(delay(1))
    def time_step_clk_gen():
        timeStepClk.next = not timeStepClk
        
    @always(timeStepClk.posedge)
    def monitor():
        if __debug__:
            print "Time: %s" % now()
        assert(Clk.val == (not oldClk.val))
        oldClk.next = Clk.val

    return instances()

def test_even_duty_cycle():
    testbench = traceSignals(even_duty_cycle)
    sim = Simulation(testbench)
    sim.run(10)


